from django.shortcuts import render

# Create your views here.
from rest_framework import viewsets
from transactions.serializers import TransactionSerialzier, TransactionApiSerializer
from transactions.models import Transaction
from rest_framework import mixins
from django.db.models import Q
from rest_framework_extensions.cache.mixins import CacheResponseMixin



class TransactionViewSet(CacheResponseMixin,mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    管理员可以看所有交易对的完整信息
    普通用户只能看脱敏信息
    """

    queryset = Transaction.objects.all()
    serializer_class = TransactionApiSerializer

    def get_queryset(self):
        """
        管理员返回所有的 其他用户查看当前股票的交易信息
        """
        if self.request.user.is_superuser:
            return Transaction.objects.all()
        return Transaction.objects.filter(stock=int(self.request.query_params.get('stock')))[0:6]

    def get_serializer_class(self):
        if self.request.user.is_superuser:
            return TransactionSerialzier
        else:
            return TransactionApiSerializer


class MyTransactionViewSet(CacheResponseMixin,mixins.ListModelMixin, viewsets.GenericViewSet):
    """
    个人用于查看自己详细交易信息的接口
    对应于历史成交
    """
    queryset = Transaction.objects.all()
    serializer_class = TransactionSerialzier

    def get_queryset(self):
        if self.request.query_params.get('stock'):
            return Transaction.objects.filter(
                Q(Q(buy_order__user_id=self.request.user.id) | Q(sell_order__user_id=self.request.user.id)) &
                Q(stock=int(self.request.query_params.get('stock'))))
        return Transaction.objects.filter(
                Q(buy_order__user_id=self.request.user.id) |
                  Q(sell_order__user_id=self.request.user.id))
